const fs = require("fs")
const path = require("path")
const inquirer = require("inquirer")
const chalk = require("chalk")
const os = require("os")


function getIPAdress() {
  var interfaces = os.networkInterfaces()
  for (var devName in interfaces) {
    var iface = interfaces[devName]
    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i]
      if (
        alias.family === "IPv4" &&
        alias.address !== "127.0.0.1" &&
        !alias.internal
      ) {
        return alias.address
      }
    }
  }
}

async function createProject() {
  if (process.env.NODE_ENV == "production") {
    if (!process.env.npm_config_target) {
      console.log("缺少版本号...")
      console.log(`npm run build --target=x.x.xxx`)
      return
    }
  }
  console.log("读取companys.conf...")
  const companys = fs.readFileSync(
    path.join(__dirname, "./companys.conf"),
    "utf-8"
  )
  const companysJSON = JSON.parse(companys)
  let choices = []
  companysJSON.forEach((item) => {
    choices.push(item.COMPANY)
  })
  console.log(process.env.NODE_ENV)
  let { repo } = await inquirer.prompt({
    //在命令行中询问客户问题
    name: "repo", //获取选择后的结果
    type: "rawlist",
    message: "请选择配置的商家",
    choices: choices,
  })

  const company = companysJSON.find((item) => item.COMPANY == repo)
  const configTemplate = `{
    "project": "${company.APP_NAME}",
    "model": "${process.env.NODE_ENV == "development" ? "dev" : "prod"}",
    "singleWebview": false,
    "homePage": "/pages/index",
    "miniApp": {
        "id": "${company.WEAPP_APPID}"
    },
    "dev": {
        "launch_path": "http://${getIPAdress()}:10086/"
    },
    "prod": {
        "launch_path": "dist/index.html"
    },
    "tabbar": ${company.TABBAR.length == 0 ? "[]" : company.TABBAR}
  }`

  console.log("********** app info ***********")
  console.log(`APP version: ${process.env.npm_config_target}`)
  console.log(configTemplate)
  console.log("********** app info ***********")

  const content = `var config = ${JSON.stringify(
    JSON.parse(configTemplate),
    null,
    2
  )}`

  fs.writeFileSync(
    path.join(__dirname, "./mui-taro/config.js"),
    content,
    "utf8"
  )
  console.log(chalk.green("config.js 替换成功"))

  let projectConfig = fs.readFileSync(
    path.join(__dirname, "./manifest.json"),
    "utf-8"
  )
  // console.log(JSON.parse(projectConfig))
  let manifest = JSON.parse(projectConfig)

  // 应用名称
  manifest.name = company.APP_NAME

  if (process.env.npm_config_target) {
    const vers = process.env.npm_config_target.split(".")
    // 应用版本名称
    manifest.version.name = `${vers[0]}.${vers[1]}`
    // 应用版本号
    manifest.version.code = parseInt(vers[2])
  }

  // 支付
  manifest.plus.distribute.plugins.payment.weixin.appid = company.WX_APPID
  manifest.plus.distribute.plugins.payment.weixin.UniversalLinks =
    company.UNIVERSL_LINKS

  // 分享
  manifest.plus.distribute.plugins.share.weixin.appid = company.WX_APPID
  manifest.plus.distribute.plugins.share.weixin.UniversalLinks =
    company.UNIVERSL_LINKS

  // oauth
  // manifest.plus.distribute.plugins.oauth.weixin.appid = company.WX_APPID
  // manifest.plus.distribute.plugins.oauth.weixin.appsecret =
  //   company.WX_APPSECRET
  // manifest.plus.distribute.plugins.oauth.weixin.UniversalLinks =
  //   company.UNIVERSL_LINKS

  fs.writeFileSync(
    path.join(__dirname, "./mui-taro/manifest.json"),
    JSON.stringify(manifest, null, 2),
    "utf8"
  )
  console.log(chalk.green("manifest.json 替换成功"))
}

createProject()
